//
//  UserService.swift
//  ShareUmbrella
//
//  Created by niupark on 2017/7/2.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import RxSwift
import SwiftyJSON

let User = UserService.sharedInstance

public enum UserStatus: Int{
    case normal = 0
    case accepting = 1
    case waiting = 2
    case accepted = 3
    case beAccepted = 4
    case inTrip = 5
    
    var tipsString:String {
        switch self {
        case .normal:
            return "正常"
        case .accepting:
            return "提供帮助中..."
        case .waiting:
            return "正在匹配帮助者..."
        case .accepted:
            return "已接受他人的帮助请求"
        case .beAccepted:
            return "已经有人提供帮助"
        case .inTrip:
            return "路途中..."
        }
    }

}

struct StatusInfo {
    var status: UserStatus = .normal
    var info:JSON! //UserStatusAction接口返回的 data数据
}

class UserService: NSObject {
    static let sharedInstance = UserService()
    private var timer:Timer?
    /// 头像
    var headLogo: Variable<String?> = Variable(nil)
    var phone: Variable<String?> = Variable("")
    var password: Variable<String?> = Variable("")
    var name: Variable<String?> = Variable("")
    var age: Variable<String?> = Variable("")
    var sex: Variable<Sex?> = Variable(.male)
    var count: Variable<String?> = Variable("0.0")
    var times: Variable<String?> = Variable("0")
    var km: Variable<String?> = Variable("0.0")
    var point: Variable<String?> = Variable("0")
    var statusInfo: Variable<StatusInfo?> = Variable(nil)
    override private init() {
        super.init()
        //监听用户登录操作
        _  = Auth.isLogin.asObservable().takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self] (isLogin) in
            guard let `self` = self else {
                return
            }
            if isLogin {
                self.startRefreshStatus()
            }else {
                self.stopRefresh()
            }
            
        })

    }
   
    ///更新头像，
    func updateheadlogo(_ imageKey: String, completion: @escaping (_ successed: Bool)-> Void) {
        var paramer:[String: Any] = [:]
        paramer["headlogo"] = imageKey
    }
    
    func getStatus(_ completed:(()->Void)? = nil) {
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.getStatus(token: Auth.token))).subscribe(onNext: {[weak self] (data) in
            //
            guard let `self` = self , let `data` = data else {
                return
            }
            print("刷新用户状态--->成功")
            var info = StatusInfo()
            info.status =  UserStatus(rawValue: data["data"]["status"].intValue) ?? .normal
            info.info = data["data"]
            self.statusInfo.value = info
            if info.status == .accepting , let _ = data["data"]["info"].dictionary {
                NotificationCenter.default.post(name: SOSNotifcation, object: info)
            }
            completed?()
            
        }, onError: {(_) in
            print("刷新用户状态-->失败")
            completed?()
        })
        
    }
    
    
    private func startRefreshStatus() {
        guard let _ = self.timer else {
            
            //5秒更新一次附近用户的信息
            self.timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { [weak self](timer) in
                guard let `self` = self else {
                    return
                }
                self.getStatus()
                self.getLastComment()
            })
            self.timer?.fire()
            return
        }
        
    }
    func getLastComment(_ completed:(()->Void)? = nil) {
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(ProvideAPI.getMyLastCommentted(token: Auth.token))).subscribe(onNext: {[weak self] (data) in
            //
            guard let `self` = self , let `data` = data else {
                return
            }
            print("获取用户评论--->成功")

            let notify = ["param1": data["data"]["param1"].stringValue, "type": data["data"]["type"].intValue] as [String : Any]
            NotificationCenter.default.post(name: RomoteNotifcation, object: nil, userInfo: notify)
            completed?()
            
            }, onError: {(_) in
                print("获取用户评论-->失败")
                completed?()
        })
        
    }
    
    private func stopRefresh() {
        guard let t = self.timer else {
            return
        }
        
        t.invalidate()
        self.timer = nil
    }
    

}
